<?php
	include_once(realpath(dirname(__FILE__).'/../conf.php'));
	include_once("$GLOBALS[dir_abstract]/ALogger.php");
	include_once("$GLOBALS[dir_class]/CCore.php");

	class CDB extends ALogger
	{
		// query counter
		var $totQueries = 0;

		// access
		var $usr;
		var $paw;
		var $grp;

		// state flag
		var $_connected = false;

		public function __construct($name = "defaultDB")
		{
			$this->name = $name;
		}

		public function __destruct()
		{
		}

		// executes a connection to the db referred to the specified user
		// returns the result of the connection
		function connect(&$usr)
		{
			if(!@mysql_connect($GLOBALS["db_host"], $usr->db_usr, $usr->db_psw))
			{
				$this->warning("impossibile connettersi a $GLOBALS[db_host]");
				return false;
			}
			if(!@mysql_select_db($GLOBALS['db_name']))
			{
				$this->warning("impossibile trovare il database $GLOBALS[db_name] in $GLOBALS[db_host]");
				return false;
			}
			$this->_connected = true;
			$this->debug("db connect $GLOBALS[db_host], $usr->db_usr, $usr->db_psw");
			return true;
		}

		// executes the specified sql
		// returns the resulted resource
		public function query($sql)
		{
			if(!$this->_connected)
			{
				$this->debug("non connesso per eseguire: $sql");
				return false;
			}
			$this->totQueries++;
			$this->debug("esecuzione query $this->totQueries: $sql");
			return mysql_query($sql);
		}

		public static function printTable(&$res)
		{
			$ret = "";
			if(!$res)
			{
				CCore::debug("[CDB::printTable]: unable to print the table \"$res\"");
				return;
			}
			$ret .= "<table border=\"1\"><tr>";
			$nfields = mysql_num_fields($res);
			for($i=0; $i<$nfields; $i++)
			{
				$field_name = mysql_field_name($res, $i);
				$ret .= "<td>$field_name</td>\n";
			}
			$ret .= "</tr>";
			while($row = mysql_fetch_array($res))
			{
				$ret .= "<tr>";
				for($i=0; $i<$nfields; $i++)
				{
					$ret .= "<td>$row[$i]</td>\n";
				}
				$ret .= "</tr>";
			}
			$ret .= "</table>";
			return $ret;
		}
	}

?>